<?php
/**
 * Created by PhpStorm.
 * User: 69548
 * Date: 2018/7/24
 * Time: 10:32
 */

namespace app\api\controller;

use Aliyun;
use app\common\controller\Api;
use think\Db;
use think\Log;
use think\Request;
use think\Loader;
use think\Cookie;
use think\Session;
use app\common\extend\Random;
use think\Validate;
class Member extends Api
{
    protected $model = null;
    private  $url='https://d.kwibon.cn/api';//测试地址

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        header('Access-Control-Allow-Origin:*');
        $this->model = model('Member');
        $uid=input('uid');
        $member_id=input('member_id');
        if  (!empty($uid)){
            $this->member_pcode=  $uid;
            $uids=db('member')->where('member_id',$uid)->find();
            if (!empty($member_id) && $uid != $member_id && $uids['member_pcode'] != $member_id ){
                db('member')->where('member_id',$member_id)->update([
                    'member_pcode'=> $uid
                ]);
            }
        }

        Log::init([
            'type'  =>  'File',
            'path'  =>  APP_PATH.'logs/'
        ]);
    }

    public function post_data($url, $data_string,$token) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, TRUE);		//表示需要response header
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);

        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                "Content-Type: application/json; charset=utf-8",
                'Authorization:'.$token,
            )
        );
        ob_start();
        curl_exec($ch);
        $return_content = ob_get_contents();
        ob_end_clean();
        //获取头部
        $header_size	= curl_getinfo($ch, CURLINFO_HEADER_SIZE);
        $headers		= substr($return_content, 0, $header_size);
        $return_content = substr($return_content,$header_size);
        //http状态码
        $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        return $return_content;
    }

    public function get_data($url,$token){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET');
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            "Content-Type: application/json; charset=utf-8",
            'Authorization:'.$token
        ));
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        $output = curl_exec($curl);
        $info = json_decode($output, true);
        return $info;
    }

    public function http_post_data($url, $data_string) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, TRUE);		//表示需要response header
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                "Content-Type: application/json; charset=utf-8",
                "Content-Length: " . strlen($data_string))
        );
        ob_start();
        curl_exec($ch);
        $return_content = ob_get_contents();
        ob_end_clean();

        //获取头部
        $header_size	= curl_getinfo($ch, CURLINFO_HEADER_SIZE);
        $headers		= substr($return_content, 0, $header_size);
        $return_content = substr($return_content,$header_size);
        //http状态码
        $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        return array($return_code, $headers,$return_content);
    }

    public function sendCurl($url, $method = 'GET', $headers = [], $data = '')
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        if (!empty($data)) {
            $sendUrl = $url . '?token=' . $data['token'].'&unionId='.$data['unionId'];
        } else {
            $sendUrl = $url;
        }
        curl_setopt($curl, CURLOPT_URL, $sendUrl);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            "Content-Type: application/json; charset=utf-8"
        ));
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        $urlArr = explode('/',$url);
        $host = $urlArr[0] . '//'. $urlArr[2];
        if (1 == strpos("$" . $host, "https://")) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        $output = curl_exec($curl);
        $info = json_decode($output, true);
        return $info;
    }

    public function object_array($array) {
        if(is_object($array)) {
            $array = (array)$array;
        }
        if(is_array($array)) {
            foreach($array as $key=>$value) {
                $array[$key] = $this->object_array($value);
            }
        }
        return $array;
    }



    /**
     * 会员登录wap
     */
    public function login(){
        $post=\request()->post();
        $member = db('member')->where('member_username',$post['country_code'].$post['username'])->find();
        $data = $this->kbxUser($post['country_code'].$post['username'],$member['kbx_id']);
        if ($data['username']!=$post['country_code'].$post['username']){
            echo $data['username'];
            echo "<br>";
            echo $post['country_code'].$post['username'];
            echo '用户不存在2';
            die;
        }
        if(empty($member)){
            return json_encode(['msg'=>'用户名不存在4','code'=>101]);
        }else{
            if($member['member_password']!=$this->loginpassword($post['password'],$member['member_password_code'])){
                $this->error('密码错误','',-1);
            }else{
                $t='';
                if (empty($member['token'])){
                    $token=md5(md5($post['username'])+md5($member['wechat_unionid'])+md5(time()).'_wap');
                    $b= db('member')->where('member_id',$member['member_id'])->update([
                        'token'=>$token,
                        'token_time'=>time()
                    ]);
                    if ($b==false) return json_encode(['msg'=>'数据写入失败','code'=>101]);
                }
                $t = db('member')->where(['member_id' =>$member['member_id']])->find();
                $Integral= db('integral')->select();

                if($t['member_pcode']==1159){
                    $partner_id = 'fl';
                }else{
                    $partner_id = 'kbx';
                }

                //计算优惠券
                $d=db('coupondetails')
                    ->alias('a')
                    ->where('a.member_id', $t['member_id'])
                    ->join('coupon d','a.coupon_id=d.coupon_id')
                    ->where('a.usestatus',0)
                    ->field('d.*,a.id,a.starttime')
                    ->select();
                $jishu=0;
                foreach ($d as $v){
                    if ($v['end_usetime'] < time()) {

                    }else {
                        $jishu++;
                    }
                }
                $img='';
                if (empty($t['thumb'])){
                    $img='';
                }else{
                    $img= db('attachment')->where('id',$t['thumb'])->find();
                    $img=$img['filepath'];
                }
                $shu=[
                    'openId'=>$t['wechat_openid'],
                    'unionId'=>$t['wechat_unionid'],
                    'member_id'=>$t['member_id'],
                    'member_username'=>$t['member_username'],
                    'member_nickname'=>$t['member_nickname'],
                    'member_integral'=>$t['member_integral'],
                    'member_money'=>$t['member_money'],
                    'is_apply'=>$t['is_apply'],
                    'member_coupon'=>$jishu,
                    'img'=>$img,
                    'token'=>$t['token'],
                    'Integral'=>$Integral,
                    'partner_id'=>$partner_id
                ];

                return json_encode(['msg'=>'登录成功','data'=>$shu,'code'=>0]);
            }
        }
    }

    //会员手机注册
    public function regTel(){
        $telphone= input('telphone');
        $country_code= input('country_code');
        $validate = new Validate(['telphone' => 'require']);
        if(!$validate->check(['telphone'=>$country_code.$telphone])){
            $this->error($validate->getError(), '', -1);
        }
        $res=Db::name('member')->where('member_phone',$country_code.$telphone)->find();
        if(!empty($res)){
            if(!empty($res['wechat_openid']) || !empty($res['wechat_unionid'])){
                return  json_encode(['msg'=>'该手机号已注册','code'=>101]);
            }
        }

        Db::startTrans();
        try{
            $d=db('code')->where('telphone',$country_code.$telphone)->find();
            $code = Random::numeric();
            if (!empty($d)){
                if ((time()-$d['time'])>60){
                    $data = $this->kbxsmscode($country_code.$telphone,$code);
                    if(empty($data)){
                        db('code')->where('telphone',$country_code.$telphone)->update([
                            'code'=>$code,
                            'time'=>time(),
                        ]);
                    }else{
                        return  json_encode(['msg'=>"发送失败",'code'=>101]);
                    }
                }else{
                    return  json_encode(['msg'=>"60秒内只能发送一次",'code'=>101]);
                }
            }else{
                $data = $this->kbxsmscode($country_code.$telphone,$code);
                if(empty($data)){
                    db('code')->insert([
                        'code'=>$code,
                        'telphone'=>$country_code.$telphone,
                        'time'=>time(),
                    ]);
                }else{
                    return  json_encode(['msg'=>"发送失败",'code'=>101]);
                }
            }
            Db::commit();
            return json_encode(['msg'=>"发送成功",'code'=>0,'data'=>['code'=>$code]]);
        }catch (\Exception $e){
            return json_encode(['msg'=>$e->getMessage(),'code'=>101]);
        }
    }

    //会员邮箱注册
    public function regEmail($email)
    {
        $email = input('email');
        $validate = new Validate(['email' => 'require|email']);
        if (!$validate->check(['email' => $email])) {
            $this->error($validate->getError(), '', -1);
        }
        $res = Db::name('member')->where('member_email', $email)->find();
        if (!empty($res)) {
            return json_encode(['msg' => '该邮箱已注册', 'code' => 101]);
        }

        Db::startTrans();
        try {
            $d = db('code')->where('email', $email)->find();
            $code = Random::numeric();
            //subject: 邮件标题（必填）
            //content: 邮件正文（必填）
            //address: 邮件接收地址，多个地址以逗号分隔（必填）
            $subject = "快帮行注册验证码";
            $content = "亲 请尽快使用你的验证码:" . $code . '验证码有效期为5分钟';
            if (!empty($d)) {
                if ((time() - $d['time']) > 60) {
                    $data = $this->kbxemailcode($subject, $content, $email);
                    if (empty($data)) {
                        db('code')->where('email', $email)->update([
                            'code' => $code,
                            'email' => $email,
                            'time' => time(),
                        ]);
                    } else {
                        return json_encode(['msg' => "发送失败", 'code' => 101]);
                    }
                } else {
                    return json_encode(['msg' => "60秒内只能发送一次", 'code' => 101]);
                }
            } else {
                $data = $this->kbxemailcode($subject, $content, $email);
                if (empty($data)) {
                    db('code')->insert([
                        'code' => $code,
                        'email' => $email,
                        'time' => time(),
                    ]);
                } else {
                    return json_encode(['msg' => "发送失败", 'code' => 101]);
                }
            }
            Db::commit();
            return json_encode(['msg' => "发送成功", 'code' => 0, 'data' => ['code' => $code]]); //$this->success("发送成功",array(),0);
        } catch (\Exception $e) {
            return json_encode(['msg' => $e->getMessage(), 'code' => 101]);
        }
    }

    //验证验证码
    public function checkCode($code){
        $code=input('code');
        $telphone=input('telphone');
        $country_code= input('country_code');
        if (!empty($telphone)){
            $dcode= db('code')->where('telphone',$country_code.$telphone)->find();
        }
        $email=input('email');
        if (!empty($email)){
            $dcode= db('code')->where('email',$email)->find();
        }
        if($code==$dcode['code']){
            $post=request()->request();

            //司导端APP登录微信商城  初次绑定手机号
            $member=Db::name('member')->where('member_phone',$country_code.$telphone)->find();
            if(!empty($member)){
                if($member['member_pcode']==1159){
                    $partner_id = 'fl';
                }else{
                    $partner_id = 'kbx';
                }

                if(!empty($member['wechat_openid']) || !empty($member['wechat_unionid'])){

                }else{
                    $list = [];
                    if (!empty($post['thumb'])){
                        if (substr($post['thumb'], 0, 7) == 'http://') {
                            $post['thumb'] = str_replace("http", "https", $post['thumb']);
                        }
                        $thumb = db('attachment')->insertGetId([
                            'filepath'=>$post['thumb'],
                        ]);
                        $list['thumb'] = $thumb;
                    }

                    if (!empty($post['qita']['nickname'])){
                        $list['member_nickname'] = $post['qita']['nickname'];
                    }

                    $list['wechat_openid'] = $post['openid'];
                    $list['wechat_unionid'] = $post['unionid'];

                    if (empty($member['token'])){
                        $token = md5(md5($member['username'])+md5($list['wechat_unionid'])+md5(time()).'_wap');
                        $list['token'] = $token;
                        $list['token_time'] = time();
                    }else{
                        $token = $member['token'];
                    }

                    db('member')->where('member_id', $member['member_id'])->update($list);

                    $log[]=[
                        '司导app用户初次微信登录绑定手机号'=>json_encode($list)
                    ];
                    Log::record($log);

                    $Integral= db('integral')->select();
                    //计算优惠券
                    $d=db('coupondetails')
                        ->alias('a')
                        ->where('a.member_id', $member['member_id'])
                        ->join('coupon d','a.coupon_id=d.coupon_id')
                        ->where('a.usestatus',0)
                        ->field('d.*,a.id,a.starttime')
                        ->select();
                    $jishu=0;
                    foreach ($d as $v){
                        if ($v['end_usetime'] < time()) {

                        }else {
                            $jishu++;
                        }
                    }

                    $shu=[
                        'openId'=>$list['wechat_openid'],
                        'unionId'=>$list['wechat_unionid'],
                        'member_id'=>$member['member_id'],
                        'member_username'=>$member['member_username'],
                        'member_nickname'=>$list['member_nickname'],
                        'member_integral'=>$member['member_integral'],
                        'member_money'=>$member['member_money'],
                        'is_apply'=>$member['is_apply'],
                        'member_coupon'=>$jishu,
                        'img'=>$post['thumb'],
                        'token'=>$token,
                        'Integral'=>$Integral,
                        'partner_id'=>$partner_id
                    ];

                    return json_encode(['msg'=>'登录成功','data'=>$shu,'code'=>0]);
                }
            }

            $shu= $this->register($post);
            $log[]=[
                '注册成功返回数据'=>json_encode($shu)
            ];
            Log::record($log);
            return json_encode($shu);
        }else{
            return json_encode(['msg'=>"验证码错误",'code'=>101]);
        }
    }


    //会员注册
    public function register($post){
        $log[]=[
            '前端post数据'=>json_encode($post)
        ];
        Log::record($log);
        $country_code=$post['country_code'];
        if (!empty($post['telphone'])){
            $list['username']=$country_code.$post['telphone'];
        }
        if (!empty($post['email'])){
            $list['username']=$post['email'];
        }
        if (!empty($post['thumb'])){
            if (substr($post['thumb'], 0, 7) == 'http://') {
                $post['thumb'] = str_replace("http", "https", $post['thumb']);
            }
            $list['thumb']=$post['thumb'];
            $thumb=db('attachment')->insertGetId([
                'filepath'=>$post['thumb'],
            ]);
        }else{
            $list['thumb']= 'https://c.kuaibangxing.com/uploads/admin/admin_thumb/20180831/4267445ac8b8c64256e8a01c47ad9b16.png';
            $thumb=2842;
        }
        if (!empty($post['nickname'])){
            $list['nickname']=$post['qita']['nickname'];
        }else{
            $list['nickname']='';
        }
        if (!empty($post['unionid'])&&!empty($post['openid'])){
            $list['wechat']=['unionidOA'=>$post['unionid'],'openidOA'=>$post['openid']];
        }else{
            $list['wechat']='';
        }
        if (empty($list)){
            return '电话号码和微信码至少填一个';
        }
        $list["origin"]="customizeApp";
        $data=[];
        $log1[]=[
            '传到注册更新接口数据'=>json_encode($list)
        ];
        Log::record($log1);

        $content=  $this->kbxUserUpdate($list);

        $log2[]=[
            '注册更新接口返回数据'=>json_encode($content)
        ];

        Log::record($log2);

        if (!empty($content['msg'])) return ['code'=>101,'msg'=>$content['msg']];

        $validate = new Validate(['email'  => 'email']);
        if(!$validate->check(['email'=>$content['username']]) ||!empty($content)){
            $data['member_phone']=$country_code.$post['telphone'];
        }else{
            $data['member_email']=$post['email'];
        }

        $member_pcode = isset($post['uid'])?$post['uid']:'';

        //非拉注册
        if (!empty($post['partner_id'])){
            if($post['partner_id']=='fl'){
                //飞拉旅行返佣账号，ID：1159（昵称夏思@飞拉旅行）
                $member_pcode = 1159;
            }
        }

        //整合返回的数据
        $data['kbx_id']=isset($content['id'])?$content['id']:'';
        $data['member_username']=isset($content['username'])?$content['username']:'';
        $data['member_nickname']=isset($post['qita']['nickname'])?$post['qita']['nickname']:$list['username'];
        $data['member_city']=isset($post['qita'])?$post['qita']['country'].$post['qita']['province'].$post['qita']['city']:'';
        $data['thumb']=$thumb;
        $data['member_pcode']=$member_pcode;
        $data['wechat_openid']=isset($post['openid'])?$post['openid']:'';
        $data['wechat_unionid']=isset($content['wechat']['unionidOA'])?$content['wechat']['unionidOA']:'';
        $data['creattime']=time();
        $data['updatetime']=strtotime(isset($content['updatedAt'])?$content['updatedAt']:'');
        $data['member_password']=isset($content['pwd'])?$content['pwd']:'';
        $data['member_password_code']=isset($content['pwd_code'])?$content['pwd_code']:'';
        $data['country_code']=$country_code;
        $data=array_filter($data);

        $log3[]=[
            '返回数据整合'=>json_encode($data)
        ];
        Log::record($log3);

        if(!empty($data['wechat_unionid'])){
            $member2=db('member')->where('wechat_unionid',$data['wechat_unionid'])->find();
        }else{
            $member2=false;
        }

        if ($member2==true){
            $member=db('member')->where('wechat_unionid',$data['wechat_unionid'])
                ->update($data);
            if ($member==true){
                $member1=db('member')->where('wechat_unionid',$data['wechat_unionid'])->find();
                if (empty($member1['token'])){
                    $token = md5(md5($member1['member_username']) + md5($member1['wechat_unionid']) + md5(time()) . '_wap');
                    $b = db('member')->where('member_id', $member1['member_id'])->update([
                        'token' => $token,
                        'token_time' => time()
                    ]);
                    if ($b == false) return json_encode(['msg' => '数据写入失败', 'code' => 101]);
                }else{
                    $token = $member1['token'];
                }
                $img='';
                if (empty($member1['thumb'])){
                    $img='';
                }else{
                    $img= db('attachment')->where('id',$member1['thumb'])->find();
                    $img=$img['filepath'];
                }
                $Integral= db('integral')->select();
                //计算优惠券
                $d=db('coupondetails')
                    ->alias('a')
                    ->where('a.member_id', $member1['member_id'])
                    ->join('coupon d','a.coupon_id=d.coupon_id')
                    ->where('a.usestatus',0)
                    ->field('d.*,a.id,a.starttime')
                    ->select();
                $jishu=0;
                foreach ($d as $v){
                    if ($v['end_usetime'] < time()) {

                    }else {
                        $jishu++;
                    }
                }
                $shu1=[
                    'openId'=>!empty($data['wechat_openid'])?$data['wechat_openid']:'',
                    'unionId'=>!empty($data['wechat_unionid'])?$data['wechat_unionid']:'',
                    'member_id'=>$member1['member_id'],
                    'member_username'=>$member1['member_username'],
                    'member_nickname'=>$member1['member_nickname'],
                    'member_integral'=>$member1['member_integral'],
                    'member_money'=>$member1['member_money'],
                    'is_apply'=>$member1['is_apply'],
                    'member_coupon'=>$jishu,
                    'img'=>$img,
                    'token'=>$token,
                    'Integral'=>$Integral,
                    'partner_id'=>!empty($post['partner_id']) ? $post['partner_id'] : 'kbx'
                ];
                $shu=[
                    'code'=>0,
                    'msg'=>'修改信息成功',
                    'data'=>$shu1
                ];
                return $shu;
            }else{
                $shu=[
                    'code'=>0,
                    'msg'=>'修改信息失败请稍后再试',
                    'data'=>''
                ];
                return $shu;
            }
        }else{
            $member=db('member')
                ->insertGetId($data);
            //如果存在orderid 那么属于下单分享，新用户注册
            if(isset($post['order_id']) && !empty($post['order_id'])){
                if($post['order_id']=='longInvite'){
                    $register_type = 3;
                }else{
                    $register_type = 1;
                }
                $new_member_list=[
                    'member_id' => $post['uid'],
                    'createtime' => time(),
                    'order_id'=> $post['order_id'],
                    'new_member_id' => $member,
                    'register_type' => $register_type,
                ];
                Db::name('share_register_log')->insert($new_member_list);
                $temp_share=Db::name('share_register')->where(['member_id'=>$post['uid'],'order_id'=> $post['order_id']])->find();
                if(!empty($temp_share)){
                    //修改记录
                    $count=Db::name('share_register_log')->where(['member_id'=>$post['uid'],'order_id'=> $post['order_id']])->count();
                    if($count == $temp_share['sharenum']){
                        Db::name('share_register')->where(['member_id'=>$post['uid'],'order_id'=> $post['order_id']])->update(['status'=>2]);
                    }
                }
            }

            Log::record($member);

            if ($member==true){
                $da=db('member')->where('member_id',$member)->find();
                $token=md5(md5($da['member_username'])+md5($da['wechat_unionid'])+md5(time()).'_wap');
                $b= db('member')->where('member_id',$da['member_id'])->update([
                    'token'=>$token,
                    'token_time'=>time()
                ]);
                if ($b==false) return ['msg'=>'数据写入失败','code'=>101];
//                $member1=db('member')->where('wechat_unionid',$data['wechat_unionid'])->find();

                $member1 = $da;
                $img='';
                if (empty($member1['thumb'])){
                    $img='';
                }else{
                    $img= db('attachment')->where('id',$member1['thumb'])->find();
                    $img=$img['filepath'];
                }

                $Integral= db('integral')->select();

                //注册领取活动判断
                $count_result=$this->couponMarket($member1['member_id'],1);

                //计算优惠券
                $d=db('coupondetails')
                    ->alias('a')
                    ->where('a.member_id', $member1['member_id'])
                    ->join('coupon d','a.coupon_id=d.coupon_id')
                    ->where('a.usestatus',0)
                    ->field('d.*,a.id,a.starttime')
                    ->select();
                $jishu=0;
                foreach ($d as $v){
                    if ($v['end_usetime'] < time()) {

                    }else {
                        $jishu++;
                    }
                }
                $shu1=[
                    'openId'=>!empty($data['wechat_openid'])?$data['wechat_openid']:'',
                    'unionId'=>!empty($data['wechat_unionid'])?$data['wechat_unionid']:'',
                    'member_id'=>$member1['member_id'],
                    'member_username'=>$member1['member_username'],
                    'member_nickname'=>$member1['member_nickname'],
                    'member_integral'=>$member1['member_integral'],
                    'member_money'=>$member1['member_money'],
                    'is_apply'=>$member1['is_apply'],
                    'member_coupon'=>$jishu,
                    'img'=>$img,
                    'token'=>$token,
                    'Integral'=>$Integral,
                    'coupon_get'=>$count_result,
                    'partner_id'=>!empty($post['partner_id']) ? $post['partner_id'] : 'kbx'
                ];
                $shu=[
                    'code'=>0,
                    'msg'=>'注册成功',
                    'data'=>$shu1
                ];
                return $shu;
            }else{
                $shu=[
                    'code'=>0,
                    'msg'=>'注册失败请稍后再试',
                    'data'=>''
                ];
                return $shu;
            }
        }
    }


    //登陆密码加密方式
    function loginpassword($password, $password_code='')
    {
        return md5(md5($password) . md5($password_code));
    }

    //注册密码加密方式
    function registerpassword($password)
    {
        $password_code=$this->randomkeys(35);
        $shu=[
            'pwd'=>md5(md5($password) . md5($password_code)),
            'pwd_code'=>$password_code
        ];
        return $shu;
    }

    //随机字符串生成方法
    public  function randomkeys($length)
    {
        $key='';
        $pattern = '1234567890abcdefghijklmnopqrstuvwxyz   
               ABCDEFGHIJKLOMNOPQRSTUVWXYZ';
        for($i=0;$i<$length;$i++)
        {
            $key .= $pattern{mt_rand(0,35)};    //生成php随机数
        }
        return $key;
    }

    //找回密码
    public function editPassword($password){
        $username = Cookie::get('username');
        if($username){
            $member = $this->model->get(['member_username'=>$username]);
            $data['password'] = password($password);
            $result = $member->save($data);
            if($result){
                $this->success('修改成功','',1);
            }else{
                $this->error('修改失败','',-1);
            }
        }else{
            $this->error('请先填写手机号或邮箱','',-1);
        }
    }

    public function login1(){
        if($this->request->port()){
            $weixin_openid = $this->request->port('weixin_openid');
        }else{
            $this->error(__('Parameter anomaly'), '', -104);
        }
    }

    //短信验证码
    public function sendSmsByAliyun($phone,$code){
        $number = input('number');//input助手函数	获取输入数据 支持默认值和过滤

        Loader::import('Alidayu.api_demo.SmsDemo',EXTEND_PATH);//对应extend目录，路径，如果你对SmsDemo类添加了命名空间可在上面 use 后在此处直接实例化

        $sms =  new Aliyun\SmsDemo();
        //设置关键的四个配置参数，其实配置参数应该写在公共或者模块下的config配置文件中，然后在获取使用，这里我就直接使用了。
        $sms->accessKeyId = 'LTAIo0DH0xQ2bkvY';
        $sms->accessKeySecret = 'Gt2l7PKr8T0uFTFrWgZAm3mFzAWQPN';
        $sms->signName = '包崇林';
        $sms->templateCode = 'SMS_95815030';
        //$mobile为手机号
        $mobile = $phone;
        $templateParam = array("code"=>$code);
        $m = $sms->send($mobile,$templateParam);
        return $m;
    }

    //邮箱验证码
    public function kbxemailcode($subject='',$content='',$address=''){
        $url=$this->url.'/client/email';
        $list=[];   //post值
        $where=[];  //组装条件
        $token = 'Bearer '.$this->kbxToken();
        if (!empty($subject)&& !empty($content)&&!empty($address)){
            $list=['subject'=>$subject,'content'=>$content,'address'=>$address];
        }else{
            return '数据错误参数为空';
        }

        $list=json_encode($list);
        $content=$this->post_data($url,$list,$token);
        $content=$this->object_array(json_decode($content));
        return $content;
    }

    //验证码
    public function kbxsmscode($phone='',$code=''){
        $url=$this->url.'/client/sms/code';
        $list=[];   //post值
        $where=[];  //组装条件
        $table=Db::name('member');  //建立表模型
        $token = 'Bearer '.$this->kbxToken();
        if (!empty($phone)&& !empty($code)){
            $list=['mobile'=>$phone,'code'=>$code];
        }
        if (empty($list)){
            return '数据错误参数为空';
        }
        $list=json_encode($list);
        $content=$this->post_data($url,$list,$token);
        trace("发送短信请求体：".$list);
        trace("发送短信返回结果：".$content);
        $content=$this->object_array(json_decode($content));
        return $content;
    }


    /**
     * 快帮行Token获取
     *
     * @param $clientId 客户端ID，由快帮行后台提前分配
     * @param $secret   根据当前时间生成的时间字符串
     * @param $timeStamp    快帮行后台提供的 秘钥+timeStamp 字符串合并后做MD5加密的结果字符串
     * $clientId='5b4f0a2322437c15382e767d',$secret='kwiBon20l8',$timeStamp=''
     */
    public function kbxToken($clientId='5b4f0a2322437c15382e767d',$secret='kwiBon20l8',$timeStamp=''){
        $url = $this->url."/auth/login/client";
        $timeStamp = date("YmdH:i",time());
        $data['clientId'] = $clientId;
        $data['timeStamp'] = $timeStamp;
        $data['secret'] = md5($secret.$data['timeStamp']);
        $data = json_encode($data);
        list($return_code,$headers,$return_content) = $this->http_post_data($url, $data);
        $content = json_decode($return_content,true);

        if($content['token']){
//            echo $content['token'];exit();
            return $content['token'];
        }else{
            $this->error(__('Server error'), '', -104);
        }
    }

    /**
     * 快帮行用户详情获取
     *
     * @param $id   用户id
     * @param string $phone
     * @param string $unionId
     */
    public function kbxUser($username='',$id='',$unionId=''){
        $url = $this->url."/client/users/getUser?";
        if(!empty($username)){
            $url=$url.'username='.urlencode($username).'&';
        }
        if (!empty($unionId)){
            $url=$url."unionidOA=$unionId&";
        }
        if(!empty($id)){
            $url=$url.'id='.$id;
        }

        $token = 'Bearer '.$this->kbxToken();
        $content = $this->post_data($url,'',$token);
        $content=$this->object_array(json_decode($content));

        return  $content;
    }

    public function kbxUser2($username='',$id='',$unionId=''){
        $url = $this->url."/client/users/getUser?";
        $username= input('username');
        $where=[];  //组装条件
        if(!empty($username)){
            $url=$url.'username='.urlencode($username).'&';
        }
        if (!empty($unionId)){
            $url=$url."unionidOA=$unionId&";
        }
        if(!empty($id)){
            $url=$url.'id='.$id;
        }

        $token = 'Bearer '.$this->kbxToken();
        $content = $this->post_data($url,'',$token);
        $content=$this->object_array(json_decode($content));
        return  json_encode($content);
    }

    //支付成功短信通知接口
    public function kbxpaysuccess($datas=''){
        $url=$this->url.'/client/sms/paysuccess';
        //mobile: 客户手机号（必填，带国家码）
        //date: 日期字符串（必填，例如"2018年8月20日"）
        //city: 目的地城市名称（必填）
        //service: 服务名称字符串（必填，例如"接机"，注意末尾不要带"服务" 两个字）
        //orderId: 订单号（必填）

        $token = 'Bearer '.$this->kbxToken();
        $list=json_encode($datas);
        $content=$this->post_data($url,$list,$token);
        $content=$this->object_array(json_decode($content));

        return  $content;
    }

    //快帮行 用户注册更新
    public function kbxUserUpdate($data=''){
        $url=$this->url.'/client/users/updateUser';
        $token = 'Bearer '.$this->kbxToken();
        $list=json_encode($data);
        $content=$this->post_data($url,$list,$token);
        $content=$this->object_array(json_decode($content));
        return $content;
    }


    //优惠券领取
    public function couponMarket($member,$mk_id,$order_id=''){

        $arr=['code'=>0,'msg'=>'获取旅行红包成功','data'=>''];
        $count_list_market=[];//可领优惠券

        $data=Db::name('coupon_marketing')->where(['mk_id'=>$mk_id])->find();
        //先判断活动状态
        if($data['status'] == 2 ){
            $arr=['code'=>1,'msg'=>'活动已结束','data'=>''];
            return $arr;
        }
        if($data['time_chose'] == 2 && $data['endtime'] < time()){
            $arr=['code'=>1,'msg'=>'活动已结束','data'=>''];
            return $arr;
        }
        if($data['time_chose'] == 2 && $data['starttime'] > time()){
            $arr=['code'=>1,'msg'=>'活动尚未开始','data'=>''];
            return $arr;
        }
        //获取优惠券
        if(empty($data['coupon_ids'])){
            $arr=['code'=>1,'msg'=>'旅行红包没有啦','data'=>''];
            return $arr;
        }else{
            $count_list_market=explode(',',$data['coupon_ids']);
        }

        //如果send_type为1 即领取,返回已领券的内容，否则返回需要凑单的人数或者人数判断
        if($data['send_type'] == 2 ){
            $temp_share=Db::name('share_register')->where(['member_id'=>$member,'order_id'=>$order_id ])->select();
            if(empty($temp_share)){
                //添加
                if(count($count_list_market) > 1){
                    $list_temp_all=[];
                    foreach ($count_list_market as $k){
                        $list_temp=[
                            'member_id'=>$member,
                            'createtime'=>time(),
                            'order_id'=>$order_id,
                            'status'=>1,
                            'sharenum'=>$data['share'],
                            'coupon_id'=>$k // 追加优惠券id
                        ];
                        array_push($list_temp_all,$list_temp);
                    }
                    Db::name('share_register')->insertAll($list_temp_all);
                }else{
                    $list_temp=[
                        'member_id'=>$member,
                        'createtime'=>time(),
                        'order_id'=>$order_id,
                        'status'=>1,
                        'sharenum'=>$data['share'],
                        'coupon_id'=>$count_list_market[0] // 追加优惠券id
                    ];
                    Db::name('share_register')->insert($list_temp);
                }
                $arr=['code'=>1,'msg'=>'还需邀请'.$data['share'].'人参与注册即可领券哦','data'=>''];
                return $arr;

            }else{
                //领取取出来，统一在优惠券领取页进行领取
                $arr=['code'=>1,'msg'=>'分享成功，快去旅行红包领取里面领取奖励吧','data'=>''];
                return $arr;
            }
        }

        $time=time();
        $w['coupon_status']=2;
        $w['etart_receivetime']=['<',$time];
        $w['end_receivetime']=['>',$time];
        $coupon_list=Db::name('coupon')->where('coupon_id','IN',$data['coupon_ids'])->where($w)->select();

        $re_data=[];//返回优惠券数据
        $set_data=[];// 进行领取数据写入
        //对每个优惠券的数量进行判断
        foreach ($coupon_list as $k){
            $temp=[
                'member_id'=>$member,
                'coupon_id'=>$k['coupon_id'],
                'starttime'=>time(),
                'usestatus'=>0
            ];

            $re_temp=[
                'coupon_id'=>$k['coupon_id'],
                'coupon_name'=>$k['coupon_name'],
                'coupon_num'=>1, //领取数量 暂定为1
                'coupon_discount'=>$k['coupon_discount'], //折扣或满减金额
                'coupon_type'=>$k['coupon_types']  //1=折扣,2=满减
            ];

            $k['num_types']=empty($k['num_types'])?2:$k['num_types'];
            //无限量 不进行验证
            if($k['num_types'] == 1){
                array_push($re_data,$re_temp);
                array_push($set_data,$temp);
            }else{
                if($k['coupon_alreadyreceived'] < $k['coupon_quantity']){
                    array_push($re_data,$re_temp);
                    array_push($set_data,$temp);

                }
            }
        }
        if(empty($re_data)) {
            $arr = ['code' => 1, 'msg' => '旅行红包已经被抢光了', 'data' => ''];
            return $arr;
        }else{
            //领取
            Db::startTrans();
            try{
                //对领取记录入库
                $da=db('coupondetails')->insertAll($set_data);
                //领取数量统计
                foreach ($set_data as $v){
                    $shu=db('coupondetails')->where('coupon_id',$v['coupon_id'])->count();
                    $gen= db('coupon')->where('coupon_id',$v['coupon_id'])->update(['coupon_alreadyreceived'=>$shu]);
                }

                if($data['send_type'] == 2 ){  //修改后， == 2的领取不走此方法
                    Db::name('share_register')->where(['member_id'=>$member,'order_id'=>$order_id ])->update(['status'=>3]);
                }

                // 提交事务
                Db::commit();
                $arr = ['code' => 0, 'msg' => '领取成功', 'data' =>$re_data];
                return $arr;

            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $arr = ['code' => 1, 'msg' => '领取失败', 'data' =>''];
                return $arr;
            }
        }

    }


    //手机登录/注册  发送验证码
    public function GetTelCode(){
        $telphone= input('telphone');
        $country_code= input('country_code');
        $validate = new Validate(['telphone' => 'require']);
        if(!$validate->check(['telphone'=>$country_code.$telphone])){
            $this->error($validate->getError(), '', -1);
        }

        Db::startTrans();
        try{
            $d=db('code')->where('telphone',$country_code.$telphone)->find();
            $code = Random::numeric();
            if (!empty($d)){
                if ((time()-$d['time'])>60){
                    $data = $this->kbxsmscode($country_code.$telphone,$code);
                    if(empty($data)){
                        db('code')->where('telphone',$country_code.$telphone)->update([
                            'code'=>$code,
                            'time'=>time(),
                        ]);
                    }else{
                        return  json_encode(['msg'=>"发送失败",'code'=>101]);
                    }
                }else{
                    return  json_encode(['msg'=>"60秒内只能发送一次",'code'=>101]);
                }
            }else{
                $data = $this->kbxsmscode($country_code.$telphone,$code);
                if(empty($data)){
                    db('code')->insert([
                        'code'=>$code,
                        'telphone'=>$country_code.$telphone,
                        'time'=>time(),
                    ]);
                }else{
                    return  json_encode(['msg'=>"发送失败",'code'=>101]);
                }
            }
            Db::commit();
            return json_encode(['msg'=>"发送成功",'code'=>0,'data'=>['code'=>$code]]);
        }catch (\Exception $e){
            return json_encode(['msg'=>$e->getMessage(),'code'=>101]);
        }
    }

    //手机登录/注册  验证验证码
    public function checkTelCode(){
        $post=request()->request();
        $code=input('code');
        $telphone=input('telphone');
        $country_code= input('country_code');
        if(empty($telphone)){
            return json_encode(['msg'=>"手机号缺少",'code'=>404]);
        }
        if(empty($country_code)){
            return json_encode(['msg'=>"区号缺少",'code'=>405]);
        }

        $dcode= db('code')->where('telphone',$country_code.$telphone)->find();

        //验证code
        if($code==$dcode['code'])
        {//验证成功
            $res=Db::name('member')->where('member_phone',$country_code.$telphone)->find();
            if(!empty($res))
            {//已注册 直接登录
                return $this->loginTel($post);
            }else{//未注册 新用户注册
                $shu= $this->register($post);

                $log[]=[
                    '注册成功返回数据'=>json_encode($shu)
                ];
                Log::record($log);

                return json_encode($shu);
            }
        }else{//验证失败
            return json_encode(['msg'=>"验证码错误",'code'=>101]);
        }
    }

    //手机号无需密码   直接登录
    protected function loginTel($post)
    {
        $member = db('member')
            ->where('member_username',$post['country_code'].$post['username'])
            ->find();

        if($member['member_pcode']==1159){
            $partner_id = 'fl';
        }else{
            $partner_id = 'kbx';
        }

        //定制系统用户不存在
        if(empty($member))
        {
            return json_encode(['msg'=>'定制系统用户不存在','code'=>401]);
        }

        $data = $this->kbxUser($post['country_code'].$post['username']);
        //订单系统用户不存在
        if ($data['username']!=$post['country_code'].$post['username'])
        {
            $list['username'] = $member['member_username'];
            if(isset($member['member_email'])){
                $list['email'] = $member['member_email'];
            }
            if(isset($member['thumb'])){
                $list['thumb'] = $member['thumb'];
            }
            if(isset($member['member_nickname'])){
                $list['nickname'] = $member['member_nickname'];
            }
            $list['origin'] = "customizeApp";
            if(isset($member['wechat_unionid'])){
                $list['wechat']['unionidOA'] = $member['wechat_unionid'];
            }
            if(isset($member['wechat_openid'])){
                $list['wechat']['openidOA'] = $member['wechat_openid'];
            }

            $content = $this->kbxUserUpdate($list);
            $log2[]=[
                '注册更新接口返回数据'=>json_encode($content)
            ];
            Log::record($log2);

            if (!empty($content['msg'])) return json_encode(['msg'=>'订单系统用户创建失败:'.$content['msg'],'code'=>402]);

            //整合返回的数据
            $kbx_id=isset($content['id'])?$content['id']:'';
            if($kbx_id!==''){
                $member = db('member')
                    ->where('member_username',$member['member_username'])
                    ->update([
                        'kbx_id'=>$kbx_id,
                    ]);
            }
        }

        if (empty($member['token'])){
            $token=md5(md5($post['username'])+md5($member['wechat_unionid'])+md5(time()).'_wap');
            $b= db('member')->where('member_id',$member['member_id'])->update([
                'token'=>$token,
                'token_time'=>time()
            ]);
            if ($b==false) return json_encode(['msg'=>'数据写入失败','code'=>101]);
        }else{
            $token = $member['token'];
        }

        //计算优惠券
        $d=db('coupondetails')
            ->alias('a')
            ->where('a.member_id', $member['member_id'])
            ->join('coupon d','a.coupon_id=d.coupon_id')
            ->where('a.usestatus',0)
            ->field('d.*,a.id,a.starttime')
            ->select();
        $jishu=0;
        foreach ($d as $v){
            if ($v['end_usetime'] < time()) {

            }else {
                $jishu++;
            }
        }
        if (empty($member['thumb'])){
            $img='';
        }else{
            $img= db('attachment')->where('id',$member['thumb'])->find();
            $img=$img['filepath'];
        }

        $Integral= db('integral')->select();
        $shu=[
            'openId'=>$member['wechat_openid'],
            'unionId'=>$member['wechat_unionid'],
            'member_id'=>$member['member_id'],
            'member_username'=>$member['member_username'],
            'member_nickname'=>$member['member_nickname'],
            'member_integral'=>$member['member_integral'],
            'member_money'=>$member['member_money'],
            'is_apply'=>$member['is_apply'],
            'member_coupon'=>$jishu,
            'img'=>$img,
            'token'=>$token,
            'Integral'=>$Integral,
            'partner_id'=>$partner_id
        ];

        return json_encode(['msg'=>'登录成功','data'=>$shu,'code'=>0]);
    }

    //司导端  鉴权
    protected function authority($clientId,$secret_code,$secret)
    {
        $authority = db("authority")->where("clientId",$clientId)->find();
        $apiCode = $authority['apiCode'];
        if(!empty($secret)){
            $code = md5($apiCode.$secret_code);//口令
            if($secret==$code){
                return true;
            }
        }
        return false;
    }

    //司导端登录   接口   获取token
    public function driverGetToken(){
        $post = request()->post();
        if (!empty($post)) {
            //验证POST字段
            //secret密钥  secret_code约定字符串
            $match_arr = array("secret","secret_code","clientId","username");
            $match_res = $this->match_post($match_arr,$post);
            if($match_res['code']==200){
                if($this->authority($post['clientId'],$post['secret_code'],$post['secret']))
                {//验证成功
                    if ($post['secret']=='' || $post['secret_code']=='' || $post['clientId']=='' || $post['username']=='') {
                        $this->error("字段不能为空",array(),415);
                    }
                    //登录注册逻辑
                    $Member = new Member();
                    $res = $Member->driverLogin($post['username']);
                    if($res['code']==0){
                        $this->success("登录成功",json_encode($res),200);
                    }else{
                        $this->error("登录失败",$res['msg'],417);
                    }
                }else{
                    $this->error("密令错误",array(),412);
                }
            }else{
                $this->error("POST字段缺少",array('missKey'=>$match_res['missKey']),$match_res['code']);
            }
        }else{
            $this->error("无数据传入",array(),413);
        }
    }

    //司导端登录   方法   静默登录/注册
    protected function driverLogin($username)
    {
        $res=Db::name('member')->where('member_phone',$username)->find();
        $log[]=[
            '司导端登录username'=>$username,
        ];
        Log::record($log);

        if(!empty($res)){//已注册 直接登录
            return $this->silentLogin($username);
        }else{//未注册 新用户注册
            return $this->silentRegister($username);
        }
    }

    //静默登录  司导端
    protected function silentLogin($username)
    {
        $member = db('member')->where('member_username',$username)->find();

        $log[]=[
            '司导端静默登录'=>$username,
            'member'=>$member,
        ];
        Log::record($log);

        //定制系统用户不存在
        if(empty($member)){
            return ['msg'=>'定制系统用户不存在','code'=>401];
        }

        if (empty($member['token'])){
            $token=md5(md5($username)+md5($member['wechat_unionid'])+md5(time()).'_wap');
            $b= db('member')->where('member_id',$member['member_id'])->update([
                'token'=>$token,
                'token_time'=>time()
            ]);
            if ($b==false) return ['msg'=>'数据写入失败','code'=>402];
        }

        //计算优惠券
        $d=db('coupondetails')
            ->alias('a')
            ->where('a.member_id', $member['member_id'])
            ->join('coupon d','a.coupon_id=d.coupon_id')
            ->where('a.usestatus',0)
            ->field('d.*,a.id,a.starttime')
            ->select();
        $jishu=0;
        foreach ($d as $v){
            if ($v['end_usetime'] < time()) {

            }else {
                $jishu++;
            }
        }
        if (empty($member['thumb'])){
            $img='';
        }else{
            $img= db('attachment')->where('id',$member['thumb'])->find();
            $img=$img['filepath'];
        }

        $Integral= db('integral')->select();

        $shu=[
            'openId'=>$member['wechat_openid'],
            'unionId'=>$member['wechat_unionid'],
            'member_id'=>$member['member_id'],
            'member_username'=>$member['member_username'],
            'member_nickname'=>$member['member_nickname'],
            'member_integral'=>$member['member_integral'],
            'member_money'=>$member['member_money'],
            'is_apply'=>$member['is_apply'],
            'member_coupon'=>$jishu,
            'img'=>$img,
            'token'=>$member['token'],
            'Integral'=>$Integral,
        ];

        return ['msg'=>'登录成功','data'=>$shu,'code'=>0];
    }

    //静默注册  司导端
    protected function silentRegister($username){
        $log[]=[
            '司导端静默注册'=>$username
        ];
        Log::record($log);

        $list['username']=$username;
        $list['thumb']= 'https://c.kuaibangxing.com/uploads/admin/admin_thumb/20180831/4267445ac8b8c64256e8a01c47ad9b16.png';
        $list['nickname']='';
        $list['wechat']='';
        $list["origin"]="customizeApp";

        $content = $this->kbxUserUpdate($list);
        if (!empty($content['msg'])) return ['code'=>401,'msg'=>$content['msg']];

        //整合返回的数据
        $data=[];
        $data['member_phone']=$username;
        $data['kbx_id']=isset($content['id'])?$content['id']:'';
        $data['member_username']=isset($content['username'])?$content['username']:'';
        $data['member_nickname']=isset($post['qita']['nickname'])?$post['qita']['nickname']:$list['username'];
        $data['member_city']=isset($post['qita'])?$post['qita']['country'].$post['qita']['province'].$post['qita']['city']:'';
        $data['thumb']=2842;
        $data['creattime']=time();
        $data['updatetime']=strtotime(isset($content['updatedAt'])?$content['updatedAt']:'');
        $data=array_filter($data);

        $log1[]=[
            '司导端静默注册写入数据'=>json_encode($data)
        ];
        Log::record($log1);

        //注册  写入
        $member=db('member')->insertGetId($data);
        Log::record($member);

        if ($member==true){
            $da=db('member')->where('member_id',$member)->find();
            $token=md5(md5($da['member_username'])+md5($da['wechat_unionid'])+md5(time()).'_wap');
            $b= db('member')->where('member_id',$da['member_id'])->update([
                'token'=>$token,
                'token_time'=>time()
            ]);
            if ($b==false) return ['msg'=>'数据写入失败','code'=>402];

            $member1 = $da;
            $img='';
            if (empty($member1['thumb'])){
                $img='';
            }else{
                $img= db('attachment')->where('id',$member1['thumb'])->find();
                $img=$img['filepath'];
            }
            $Integral= db('integral')->select();

            //注册领取活动判断
            $count_result=$this->couponMarket($member1['member_id'],1);

            //计算优惠券
            $d=db('coupondetails')
                ->alias('a')
                ->where('a.member_id', $member1['member_id'])
                ->join('coupon d','a.coupon_id=d.coupon_id')
                ->where('a.usestatus',0)
                ->field('d.*,a.id,a.starttime')
                ->select();
            $jishu=0;
            foreach ($d as $v){
                if ($v['end_usetime'] < time()) {

                }else {
                    $jishu++;
                }
            }
            $shu1=[
                'openId'=>!empty($data['wechat_openid'])?$data['wechat_openid']:'',
                'unionId'=>!empty($data['wechat_unionid'])?$data['wechat_unionid']:'',
                'member_id'=>$member1['member_id'],
                'member_username'=>$member1['member_username'],
                'member_nickname'=>$member1['member_nickname'],
                'member_integral'=>$member1['member_integral'],
                'member_money'=>$member1['member_money'],
                'is_apply'=>$member1['is_apply'],
                'member_coupon'=>$jishu,
                'img'=>$img,
                'token'=>$member1['token'],
                'Integral'=>$Integral,
                'coupon_get'=>$count_result
            ];
            $shu=[
                'code'=>0,
                'msg'=>'注册成功',
                'data'=>$shu1
            ];

            $log2[]=[
                '司导端登录返回数据'=>$shu
            ];
            Log::record($log2);
        }else{
            $shu=[
                'code'=>0,
                'msg'=>'注册失败请稍后再试',
                'data'=>''
            ];
        }
        return $shu;
    }


    //小程序获取公众号openid
    public function getOpenid(){
        $post = $this->request->post();
        $unionid  = $post['unionid'];

        $member = db("member")->where("wechat_unionid",$unionid)->find();
        $wechat_openid = !empty($member['wechat_openid']) ? $member['wechat_openid'] : '';

        return json_encode(['msg'=>"获取成功",'code'=>0,'data'=>['wechat_openid'=>$wechat_openid]]);
    }

}